package conversation

import (
	"context"
	"coze_for_sdk/config"
	"coze_for_sdk/controller"
	"coze_for_sdk/controller/auth"
	"coze_for_sdk/logger"
	"coze_for_sdk/model"
	"time"

	"github.com/coze-dev/coze-go"

	"github.com/gin-gonic/gin"
)

func Create(c *gin.Context) {

	token := auth.GetCozeAccessToken()
	if token == "" {
		controller.Fail(c, controller.BusinessError, "get access token error")
		return
	}
	authCli := coze.NewTokenAuth(token)
	botID := config.DefaultConfig.Coze.BotID

	// Init the Coze client through the access_token.
	cozeCli := coze.NewCozeAPI(authCli, coze.WithBaseURL(config.DefaultConfig.Coze.ApiBase))
	ctx := context.Background()

	// 发布机器人
	// publishResp, err := cozeCli.Bots.Publish(ctx, &coze.PublishBotsReq{
	// 	BotID:        botID,
	// 	ConnectorIDs: []string{"1024"},
	// })
	// if err != nil {
	// 	fmt.Println("Error publishing bot:", err)
	// 	return
	// }

	// Create a new conversation
	resp, err := cozeCli.Conversations.Create(ctx, &coze.CreateConversationsReq{BotID: botID})
	if err != nil {
		logger.Error("create conversations error:%s ", err.Error())
		controller.Fail(c, controller.BusinessError, "create conversations error")
		return
	}

	//入库
	userId := c.GetInt("user_id")

	db := model.GetInstance().GetDB()
	db.Model(&model.CozeConversation{}).
		Create(&model.CozeConversation{
			ConversationId: resp.Conversation.ID,
			UserId:         userId,
			Status:         model.CozeConversationStatusActive,
			CreatedAt:      time.Now(),
			UpdatedAt:      time.Now(),
		})

	controller.Success(c, map[string]string{
		"conversation_id": resp.Conversation.ID,
	})
}
